package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.exception.BaseException;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.mapper.GroupItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.CheckPageQueryDTO;
import com.itheima.pojo.CheckItemVO;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemMapper checkItemMapper;
    @Autowired
    private GroupItemMapper groupItemMapper;
    /**
     * 新增检查项
     * @param checkItem
     */
    public void save(CheckItem checkItem) {
        checkItemMapper.insert(checkItem);
    }

    /**GlobalExceptionHandler
     * 检查项批量删除
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            List<Integer> groupIds = groupItemMapper.getByItem(id);
            if (groupIds.size() != 0) {
                throw new BaseException(MessageConstant.DELETE_CHECKITEM_FAIL);
            }
        }

        checkItemMapper.deleteById(ids);
    }

    /**
     * 根据主键进行查询
     * @param id
     * @return
     */
    public CheckItem geyById(Long id) {
        CheckItem checkItem = checkItemMapper.getById(id);
        return checkItem;
    }

    /**
     * 修改检查项
     * @param checkItem
     */
    public void updateById(CheckItem checkItem) {
        checkItemMapper.update(checkItem);
    }

    /**
     * 检查项分页查询
     * @param queryPageBean
     * @return
     */
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckItemVO> page = checkItemMapper.pageQuery(queryPageBean);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 检查项查询
     * @return
     */
    public List<CheckItem> findAll() {
        List<CheckItem> CheckItems = checkItemMapper.findAll();
        return CheckItems;
    }

    /**
     * 根据检查组来查询检查项
     * @param checkgroupId
     * @return
     */
    public List<Integer> itemByGroupId(Integer checkgroupId) {
        List<Integer> ids = groupItemMapper.itemByGroupId(checkgroupId);
        return ids;
    }
}
